<?php
/*
 * 词条类
 * @package    company
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 64d36045e5767bc31932a726502f763d3f3dc0cf $
 */
class CompanyEntry {
	private static $_table;
	private static $_tableEdition;

	/**
	 * 文档存储的主表
	 * @return string
	 */
	private static function _getTable() {
		if (!empty(self::$_table)) {
			return self::$_table;
		} else {
			self::$_table = Table::name(Table::NAME_MERCHANT_DOC);
			return self::$_table;
		}
	}

	/**
	 * 版本存储的主表
	 * @return string
	 */
	private static function _getTableEdition() {
		if (!empty(self::$_tableEdition)) {
			return self::$_tableEdition;
		} else {
			self::$_tableEdition = Table::name(Table::NAME_MERCHANT_EDITION);
			return self::$_tableEdition;
		}
	}

	/**
	 * 添加词条信息
	 * @param $companyInfo
	 * @param $category
	 * @return bool|int|string
	 */
	public static function add($companyInfo) {
		global $db;
		$table = self::_getTable();
		if ($db->query(Sql::insert($table, $companyInfo))){
			$did= $db->insertId();
			return $did;
		} else {
			return false;
		}
	}



	/**
	 * 获取词条的类别数组
	 * @param        $did
	 * @param string $eid
	 * @param string $type
	 * @return array|bool|string
	 */
	public static function getCatId($did,$eid='',$type='') {
		global $db;
		$table = Table::name(Table::NAME_MERCHANT_CATID);
		/*没有版本id, 就获取正在使用的*/
		if(!$eid) $eid = CompanyEntry::getDocEditionId($did);
		$sql = "select catid from $table where did=$did and eid=$eid";
		foreach($db->getAll($sql) as $val) {
			$arr[]=$val['catid'];
		}
		$arr = array_unique($arr);

		/*返回array*/
		if($type=='arr') return $arr;

		/*返回str*/
		$str = implode(',',$arr);
		return $str;
	}

	/**
	 * 添加企业库类别
	 * @param $category
	 * @param $did
	 * @param $eid
	 * @return bool
	 */
	public static function addCategory($category,$did,$eid,$userName,$userId){
		global $db;
		$table = Table::name(Table::NAME_MERCHANT_CATID);
		$time = time();
		if($category){
			foreach($category as $catid) {
				$sql = "INSERT INTO {$table} (did,eid,catid,author,authorid,time) VALUES ($did,$eid,$catid,'$userName',$userId,$time)";
				$db->query($sql);
			}
		}else{
			Prompt::message("你为什么不选类别？！");
		}
		return true;
	}


	/**
	 * 删除企业库类别
	 * @param $did
	 * @param $eid
	 * @return bool
	 */
	public static function deleteCategory($did,$eid){
		global $db;
		$table = Table::name(Table::NAME_MERCHANT_CATID);
		$db->query("delete from $table where did=$did and eid=$eid");
		return true;
	}

	/**
	 * 获取企业库主营范围
	 * @param $cates
	 * @return string
	 */
	public static function getBusiness($cates) {
		foreach($cates as $v) {
			$com_business[]= CategoryModule::getCacheCategoryName(25,$v);
		}
		$com_business = implode(',',$com_business);
		return $com_business;
	}



	/**
	 * 删除编辑器草稿
	 * @param $did
	 * @param $authorid
	 * @return bool
	 */
	public static function deleteDraft($did,$authorid){
		global $db;
		$table = Table::name(Table::NAME_MERCHANT_DRAFT);
		$db->query("delete from $table where did=$did and authorid=$authorid");
		return true;
	}

	/**
	 * 获取一条信息
	 * @param $title
	 * @return array|null
	 */
	public static function getByTitle($title) {
		global $db;
		$table = self::_getTable();
		return $db->getOne("SELECT * FROM {$table} WHERE title='$title'");
	}

	/**
	 * 组成树状结构
	 * @return array
	 */
	public static function cateCateTree(){
		return Ext::genTree(PCache::read('category-25.php'), 'catid');
	}

	/**
	 * 根据id获取条目信息
	 * @param        $did
	 * @param string $condition
	 * @return array|null
	 */
	public static function getByid($did, $condition = ''){
		global $db;
		$table = self::_getTable();
		$sql="select * from {$table} where did=$did";
		if ($condition) {
			$sql .= ' and '.$condition;
		}
		return $db->getOne($sql);
	}

	/**
	 * 获取词条当前版本id
	 * @param $did
	 * @return null
	 */
	public static function getDocEditionId($did) {
		global $db;
		$table = self::_getTable();
		$sql = "select eid from $table where did=$did";
		return $db->getVar($sql);
	}


	/**
	 * 文档ID
	 * @param $docId
	 * @return array|null
	 */
	public static function getItemAndEdition($docId){
		global $db;
		$table = self::_getTable();
		$tableEdition = self::_getTableEdition();
		$sql="select
				t.did,
				t.eid,
				t.title,
				t.summary,
				t.company_thumb,
				t.company_size,
				t.company_year,
				t.company_type,
				t.company_unit,
				t.company_money,
				t.company_areaid,
				t.company_address,
				t.company_contact,
				t.company_telephone,
				t.company_mail,
				t.company_business,
				te.content,
				t.author,
				t.authorid,
				t.time
			from
				{$table} t, {$tableEdition} te
			where
				t.did={$docId}
				and t.eid = te.eid ";
		return $db->getOne($sql);
	}



	/**
	 * 获取版本信息
	 * @param $eid
	 * @return array|null
	 */
	public static function getPreview($eid) {
		global $db;
		$table = self::_getTable();
		$tableEdition = self::_getTableEdition();
		$sql="select * from {$table} t, {$tableEdition} te where te.eid = {$eid} and t.did=te.did";
		return $db->getOne($sql);
	}

	/**
	 * 获取公司id
	 * @param $companyName
	 * @return null
	 */
	public static function getDocId($companyName) {
		global $db;
		$table = self::_getTable();
		$sql = "select did from {$table} where title='$companyName'";
		return $db->getVar($sql);
	}

	/**
	 * 检测重命名
	 * @param $companyName
	 * @return bool
	 */
	public static function decideCompanyName($companyName) {
		global $db;
		$table = Table::name(Table::NAME_MEMBER);
		$sql = "select * from {$table} where company='$companyName'";
		if($db->getOne($sql))   return false;
		if($db->getOne("select * from xd_upgrade where company='$companyName'"))	return false;
		if($db->getOne("select * from xd_company where company='$companyName'")) {
			return false;
		}else{
			return true;
		}
	}

	/**
	 * 获取提交按钮的类型 创建/编辑
	 * @param $did
	 * @return int
	 */
	public static function getSubmitType($did) {
		global $db;
		$table = Table::name(Table::NAME_MERCHANT_EDITION);
		$sql = "select * from $table where did=$did";
		if($db->getOne($sql)) {
			return 1;
		}else{
			return 0;
		}
	}

	/**
	 * 检测 企业库重命名
	 * @param        $name
	 * @param string $tableName
	 * @return bool
	 */
	public static function decideMerchantName($name,$tableName='doc') {
		global $db;
		if($tableName=='doc') {
			$table = Table::name(Table::NAME_MERCHANT_DOC);
		}elseif($tableName=='edition') {
			$table = Table::name(Table::NAME_MERCHANT_EDITION);
		}
		$sql = "select * from $table where title=$name";
		if($db->getOne($sql)) {
			return false;
		}else{
			return true;
		}
	}

	/**
	 * 获取企业信息
	 */
	public static function getCompanyInfo($title) {
		global $db;
		$table = Table::name(Table::NAME_COMPANY);
		$sql = "select * from $table where company='$title'";
		return $db->getOne($sql);
	}

	/**
	 * 获取上一个 或 下一个
	 */
	public static function getTopDown($table,$id,$type='down',$where='did') {
		global $db;
		if($type=='top') {
			$type = '<';
			$order = "ORDER BY $where DESC";
		}elseif($type=='down') {
			$type = '>';
			$order = "ORDER BY $where ASC";
		}else{
			return false;
		}
		$sql = "SELECT $where FROM $table WHERE $where $type $id $order LIMIT 1 ";
		return $db->getVar($sql);
	}

	public static function getIndexCompanyInfo($id=3836,$modulId=25,$num='30',$hot='', $hasThumb = '') {
		global $db;
		$table = TABLE::name(TABLE::NAME_MERCHANT_DOC);
		$tableCatid = TABLE::name(TABLE::NAME_MERCHANT_CATID);
		$CatIds = CategoryModule::getArrChildid($id,$modulId);

		$hasThumbSql =$hasThumb? " and d.company_thumb !=''":'';

		//假如是热门Tag
		if($hot){
			$sql = "select d.did,d.title,d.company_thumb from $table d,$tableCatid c where d.did=c.did AND c.catid IN($CatIds) and d.authority=1 and d.level=0 and c.authority=1 {$hasThumbSql} GROUP BY d.did ORDER BY d.did DESC LIMIT 0,$num";
			$arr = $db->getAll($sql, 'CACHE', 800);
			foreach($arr as $key => $val) {
				$company[$key]['id'] = $val['did'];
				$company[$key]['name'] = $val['title'];
				$company[$key]['thumb'] = $val['company_thumb'];
			}
			return $company;

		}else{

			$sql = "select d.did,d.title from $table d,$tableCatid c where d.did=c.did AND c.catid IN($CatIds) and d.authority=1 and d.level=0 and c.authority=1 {$hasThumbSql} GROUP BY d.did ORDER BY d.did DESC LIMIT 0,$num";
			$arr = $db->getAll($sql, 'CACHE', 800);
			$num = $num / 2;
			foreach($arr as $key => $val) {
				if($key < $num)
					$company[1][$val['did']] = $val['title'];
				else
					$company[2][$val['did']] = $val['title'];
			}
			return $company;

		}

	}


	/**
	 * 通过id 获取 企业库显示数据
	 * @param $id
	 */
	public static function getShowInfoById($id) {
		global $subtitles;
		$did = $id;
		$companyInfo = CompanyEntry::getItemAndEdition($did);
		if (!$companyInfo) {
			Prompt::message('不正确的数据传入!','goback');
		}
		$subtitles = array();
		$oldCompanyInfo = $companyInfo;

		//显示目录
		if (preg_match_all("/(<h1.*?>)(.*?)(<.+?>)/si", $companyInfo['content'], $matches)) {
			foreach($matches[1] as $v)	$str .= $v;
			preg_match_all("|<h1 id=\"cat(.*?)\" class=\"com-hd\">|", $str, $m);
			foreach($m[1] as $k => $v) $subtitles[$v] = trim($matches[2][$k]);

			foreach($subtitles as $k => $match) {
				$companyInfo['content'] = preg_replace(
					"/<h1 id=\"cat{$k}\" class=\"com-hd\">/",
					"<h1 id=\"cat{$k}\" class=\"com-hd\"><span class=\"hdwiki_edit_item item_{$k}\"><a class=\"edit-part fn-right\" href=\"editsection.php?id=$id&tid={$k}\">编辑本段</a></span>",
					$companyInfo['content'],
					1
				);
			}
		}
		return $companyInfo;
	}


	/**
	 * 通过 名企旧数据, 获取现在企业库的ID
	 * @param $homepage
	 * @return null
	 */
	public static function getIdByHomepage($homepage) {
		global $db;
		$table = Table::name(Table::NAME_COMPANY);
		$title = $db->getVar("select company from $table where username='$homepage'");
		$table = Table::name(Table::NAME_MERCHANT_DOC);
		$id = $db->getVar("select did from $table where title='$title'");
		return $id;
	}

}